import 'dart:io';

import 'package:convergence_media/features/api/apis/news_csavs_api.dart';
import 'package:convergence_media/features/app/repository/app_config_repository.dart';
import 'package:convergence_media/features/config/errors/login_errors.dart';
import 'package:convergence_media/features/user/repositories/token_repository.dart';
import 'package:dio/dio.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'news_interceptor.g.dart';

@riverpod
NewsInterceptor newsInterceptor(NewsInterceptorRef ref) => NewsInterceptor(
      appConfigRepository: ref.watch(appConfigRepositoryProvider),
      tokenRepository: ref.watch(tokenRepositoryProvider),
      newsCsavsApi: ref.watch(newsCsavsApiProvider),
    );

/// {@template news_interceptor}
/// 圈子的网络请求拦截器
/// {@endtemplate}
class NewsInterceptor extends QueuedInterceptor {
  /// {@macro news_interceptor}
  NewsInterceptor({
    required AppConfigRepository appConfigRepository,
    required TokenRepository tokenRepository,
    required NewsCsavsApi newsCsavsApi,
  })  : _appConfigRepository = appConfigRepository,
        _tokenRepository = tokenRepository,
        _newsCsavsApi = newsCsavsApi;

  final NewsCsavsApi _newsCsavsApi;
  final TokenRepository _tokenRepository;
  final AppConfigRepository _appConfigRepository;

  @override
  Future<void> onError(
    DioException err,
    ErrorInterceptorHandler handler,
  ) async {
    if (err.response?.statusCode == HttpStatus.unauthorized) {
      // 尝试主 token 刷新后重试
      final currentHashId = _appConfigRepository.getCurrentHashId();
      if (currentHashId == null) {
        throw AuthException.withoutToken();
      }
      final mainToken = await _tokenRepository.getMainToken(currentHashId);
      if (mainToken == null) {
        throw AuthException.withoutToken();
      }

      // TODO(lilua): 登录失败重试逻辑
      // try {
      //   final loginResponse = await _newsCsavsApi.postLoginMobile(mainToken);
      //   _newsCsavsApi.postLoginMobile(loginResponse.d!.token);
      // } on DioException catch (e) {
      //   logger.d('post拦截器:$e');
      //   throw NotLoginException();
      // } catch (e) {
      //   logger.e(e);
      // }
    } else {
      super.onError(err, handler);
    }
  }
}
